﻿using System;
using System.DHTML;
using Sys;
using Sys.UI;
using Sys.Mvc;

using JQuerySharp;
using VietPublisher.Scripts.Resources;

static public class SC_Account
{
    static public RegularExpression IdCardNo1 = new RegularExpression(@"^\d{6}$");
    static public RegularExpression IdCardNo2 = new RegularExpression(@"^\d{7}$");
    public static string ControllerUrl = "Account";

    #region 사용자관리

    public static void SearchEmpList(Dictionary form)
    {
        //UIHelper.SubmitAjax(form, "Get", null, null, null);
        Script.Literal("document.forms[0].submit();");
    }

    /// <summary>
    /// CLick on 
    /// </summary>
    /// <param name="cell"></param>
    public static void GenerateLogin(InputElement input, string userNameId, string empCode)
    {
        //string userName = Utils.GetInputValue(userNameId);
        string userName = userNameId;
        if (userName == "")
        {
            Script.Alert("사용자ID를 입력 하여 주십시오.");
            return;
        }

        // check for dup id
        Utils.ShowProgressBar();

        string href = SC_Common.BasePath + ControllerUrl + "/CheckDuplicateUserName?userName=" + userName;
        jQuery.GetJSON(href, new Dictionary(), (Function)(object)new GenericOneArgDelegate(delegate(object data)
        {
            Utils.HideProgressBar();
            bool exists = (bool)Script.Literal("data.Exists");
            if (exists)
            {
                Script.Alert("사용자ID 이미 있습니다.");
                return;
            }
            else
            {
                href = SC_Common.BasePath + ControllerUrl + string.Format("/InputPasswordPopup?useType=0&empCode={0}&userName={1}", empCode, userName);

                // ask for password
                Utils.OpenWinCenter("InputPass", href, 350, 150);
            }
        }));

    }

    /// <summary>
    /// Check password logic
    /// </summary>
    public static void CheckInputPassword(string userName)
    {

        string pwd = ((InputElement)Document.GetElementById("OldPassword")).Value;
        string newPwd = ((InputElement)Document.GetElementById("NewPassword")).Value;
        string newConfirmPwd = ((InputElement)Document.GetElementById("ConfirmPassword")).Value;        

        if (newPwd != newConfirmPwd)
        {            
            Script.Alert("비밀번호가 일치 하지 않습니다.");
            return;
        }

        if (newPwd.Length < 6)
        {         
            Script.Alert("비밀번호가 6자리이상 입력 해야 합니다.");
            return;
        }


        // check for dup id
        Utils.ShowProgressBar();

        string href = SC_Common.BasePath + ControllerUrl + string.Format("/CheckPassword?userName={0}&password={1}&dt={2}", userName, pwd, new DateTime());
        jQuery.GetJSON(href, new Dictionary(), (Function)(object)new GenericOneArgDelegate(delegate(object data)
        {
            Utils.HideProgressBar();
            bool exists = (bool)Script.Literal("data.Exists");
            if (!exists)
            {
                //Script.Alert("Password is not exist !");
                Script.Alert(Common.SC_Account_InvalidPassword);
                return;
            }
            else
            {
                
                href = SC_Common.BasePath + ControllerUrl + string.Format("/ChangePassword?userName={0}&password={1}&dt={2}", userName, newPwd,new DateTime());
                UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
                {
                    
                    if (context.request.Executor.ResponseData == "True")
                    {
                        Script.Alert(Common.OperationSuccess);
                        Utils.CloseWindow();
                        // refresh row
                    }
                }), null);
            }
        }));

        //string userName = Utils.GetInputValue("UserName");
      
        //if (useType == 0)
        //{
        //   // string empCode = Utils.GetInputValue("EmpCode");
        //  //  OnInputPasswordComplete(empCode, userName, pwd);
        //}
        //else
        //{
          //  OnChangeUserPassword(userName, pwd);
        //}

    }

    public static void OnInputPasswordComplete(string empCode, string userName, string password)
    {
        Utils.ShowProgressBar();

        // generate id and return
        string href = SC_Common.BasePath + ControllerUrl + string.Format("/CreateUser?empCode={0}&userName={1}&password={2}", empCode, userName, password);
        jQuery.GetJSON(href, new Dictionary(), (Function)(object)new GenericOneArgDelegate(delegate(object returnData)
        {
            Utils.HideProgressBar();

            bool success = (bool)Script.Literal("returnData.Success");
            string message = (string)Script.Literal("returnData.Message");

            if (!success)
            {
                Script.Alert(message);
            }
            else
            {
                Script.Alert("사용자ID 생성 완료 되었습니다.");

                // refresh
                Utils.ReloadOpenerWindow();
                Utils.CloseWindow();
            }

        }));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="userName"></param>
    public static void OpenChangePassword(string userName)
    {
        string href = SC_Common.BasePath + ControllerUrl + string.Format("/ChangePasswordPopup?userName={0}", userName);

        // ask for password
        Utils.OpenWinCenter("ChangePasswordPopup", href, 350, 150);
    }

    /// <summary>
    /// Change new password
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="newPassword"></param>
    public static void OnChangeUserPassword(string userName, string newPassword)
    {
        
        string href = SC_Common.BasePath + ControllerUrl + string.Format("/ChangePassword?userName={0}&password={1}", userName, newPassword);
        UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
            {
                if (context.request.Executor.ResponseData == "")
                {
                    Script.Alert(Common.OperationSuccess);
                    Utils.CloseWindow();
                    // refresh row
                }
            }), null);
    }

    /// <summary>
    /// Delete users
    /// </summary>
    /// <param name="userName"></param>
    public static void DeleteUser(string userName)
    {

        #region  check if Item is not checked
        if (userName == "")
        {
            Script.Alert(Common.SC_AccountNotSelectItem);//alert "you must be choose one Account"
            return;
        }
        #endregion

        if (Script.Confirm(Common.DeleteConfirm))
        {
            #region Can not delete userName is "admin"
            if (userName.ToLowerCase() == "admin")
            {
                Script.Alert(Common.SC_Account_CantDeleteAdminAccount);
                return;
            }
            #endregion

            if (userName != "")
            {
                #region delete 1 item with userName
                string href = SC_Common.BasePath + ControllerUrl + string.Format("/DeleteUser?userName={0}", userName);
                UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
                {
                    if (context.request.Executor.ResponseData == "")
                    {
                        Script.Alert(Common.OperationSuccess);
                        Utils.ReloadWindow();
                    }
                    else
                    {
                        Script.Alert(Common.OperationFailed);
                        return;
                    }
                }), null);
                #endregion
            }
        }//close confirm

    }

    /// <summary>
    /// Stop users
    /// </summary>
    /// <param name="userName"></param>
    public static void StopUser(string userName)
    {

        #region  check if Item is not checked
        if (userName == "")
        {
            Script.Alert(Common.SC_AccountNotSelectItem);//alert "you must be choose one Account"
            return;
        }
        #endregion

        if (Script.Confirm(Common.StopConfirm))
        {
            #region Can not delete userName is "admin"
            if (userName.ToLowerCase() == "admin")
            {
                Script.Alert(Common.SC_Account_CantStopAdminAccount);
                return;
            }
            #endregion

            if (userName != "")
            {
                #region delete 1 item with userName
                string href = SC_Common.BasePath + ControllerUrl + string.Format("/StopUser?userName={0}", userName);
                UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
                {
                    if (context.request.Executor.ResponseData == "")
                    {
                        Script.Alert(Common.OperationSuccess);
                        Utils.ReloadWindow();
                    }
                    else
                    {
                        Script.Alert(Common.OperationFailed);
                        return;
                    }
                }), null);
                #endregion

            }


            // Script.Alert(Common.OperationSuccess);
        }//close confirm

    }

    public static void UnlockAllUsers()
    {
        string href = SC_Common.BasePath + ControllerUrl + "/UnlockAllUsers";
        UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
        {
            if (context.request.Executor.ResponseData == "")
            {
                Script.Alert(Common.SC_Account_UnlockAllUsers);
            }
            else
            {
                Script.Alert(context.request.Executor.ResponseData);
            }

        }), null);
    }

    public static void SyncUsersWithAD()
    {
        //if (Script.Confirm(Common.SyncUsersWithADMsg))
        //{
        //    string href = SC_Common.BasePath + ControllerUrl + "/SyncUsersWithAD";
        //    UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
        //        {
        //            if (context.request.Executor.ResponseData == "")
        //            {
        //                Script.Alert(Common.SyncUserWithADCompleted);
        //            }
        //            else
        //            {
        //                Script.Alert(context.request.Executor.ResponseData);
        //            }

        //        }), null);
        //}
    }

    /// <summary>
    /// Generate allusers with default password
    /// </summary>
    public static void GenerateUsers()
    {
        //if (Script.Confirm(Common.SyncUsersWithADMsg))
        //{
        //    Utils.ShowProgressBar();

        //    // generate id and return
        //    string seed = Math.Floor(Math.Random() * 11).ToString();
        //    string href = SC_Common.BasePath + ControllerUrl + "/GenerateUserDefault?seed=" + seed;
        //    jQuery.GetJSON(href, new Dictionary(), (Function)(object)new GenericOneArgDelegate(delegate(object returnData)
        //    {
        //        Utils.HideProgressBar();

        //        bool success = (bool)Script.Literal("returnData.IsOK");
        //        string message = (string)Script.Literal("returnData.ErrorMsg");

        //        if (!success)
        //        {
        //            Script.Alert(message);
        //        }
        //        else
        //        {
        //            Script.Alert("전체 사용자 생성 완료 되었습니다.");
        //            Utils.ReloadWindow();
        //        }

        //    }));
        //}
    }

    public static void UpdateApprSignImgDefault()
    {
        //if (Script.Confirm(Common.UpdateSignImageAll))
        //{
        //    Utils.ShowProgressBar();

        //    // generate id and return
        //    string href = SC_Common.BasePath + ControllerUrl + "/UpdateApprSignImgDefault";
        //    UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
        //    {
        //        Script.Alert(Common.UpdateSignImageAllCompleted);
        //        Utils.ReloadWindow();
        //    }), null);
        //}
    }

    #endregion

    #region Login, Logout

    public static void LogOff()
    {
        Utils.Navigate(SC_Common.BasePath + ControllerUrl + "/LogOff");
    }

    public static void DoLogin(Dictionary form)
    {
        ItemInfor[] items = new ItemInfor[] { 
            new ItemInfor("UserName", true, 100, null, ValueType.Text, null),
            new ItemInfor("Password", true, 100, null, ValueType.Text, null)
        };

        if (UIHelper.ValidateItems(items, true))
        {
            Script.Eval("document.forms['formLogin'].submit();");
        }
    }

    #endregion

    #region Open Account Detail
    public static void OpenAccountDetail(string empCode)
    {
        string href = string.Format("/AccountDetail?empCode={0}", empCode);
        Utils.Navigate(SC_Common.BasePath + ControllerUrl + href);

    }
    #endregion

    #region Back To List
    public static void BackList()
    {
        Utils.Navigate(SC_Common.BasePath + ControllerUrl);
    }
    #endregion

    #region open popup Register an Account
    public static void AccountRegistPop(string link)
    {
        //int width = (Window.Screen.AvailWidth);
        //int height = (Window.Screen.AvailHeight);
        int width = 800;
        int height = 750;
        Utils.OpenWinCenter("", link, width, height);
        // Window.Open(link, "", "menubar=0,status=0,resizable=0,scrollbars=0,directories=1,location=0,width=" + width.ToString() + ",height=" + height.ToString() + ",left=" + 0 + ",top=" + 0);
    }
    #endregion

    #region admin add new an Account
    public static void DoRegisterPop(Dictionary form, String userName)
    {
        DoRegister(form);//save data
        // return a list of account
    }
    #endregion

    #region Register, CheckDuplicateEmail, Empcode
    public static void DoRegister(Dictionary form)
    {
        ItemInfor[] itemBoardContent = new ItemInfor[] {
            new ItemInfor("UserName", true, 20, null, ValueType.NText, null),
            new ItemInfor("Password", true, 20, null, ValueType.Text, null),
            new ItemInfor("EmpName", true, 20, null, ValueType.Text, null),
            new ItemInfor("EmpCode", true, 6, null, ValueType.Text, null),           
            new ItemInfor("BirthDate", false, 15, null, ValueType.DateTime, null),
            new ItemInfor("HomePhone", false, 15, null, ValueType.Number, null),
            new ItemInfor("MobilePhone", false, 20, null, ValueType.Number, null),
            new ItemInfor("ContactAddress",false,40, null, ValueType.Text,null),
            new ItemInfor("Address", false,40, null, ValueType.Text, null),
        };

        //validate for IDCardNo
        ItemInfor[] itemRecvIDCardNo = new ItemInfor[] {
                new ItemInfor("IdCardNo1", true, 6, IdCardNo1, ValueType.Number, null),
                new ItemInfor("IdCardNo2", true, 7, IdCardNo2, ValueType.Number, null),
            };

        Utils.SetInputValue("Email", Utils.GetInputValue("txtEmail") + "@kwangjin-faurecia.com");


        if (UIHelper.ValidateItems(itemBoardContent, true))
        {
            #region validate for IdCard
            //Get Value IdCardNo
            string id1 = Utils.GetInputValue("IdCardNo1");
            string id2 = Utils.GetInputValue("IdCardNo2");
            string id = id1.Trim() + "-" + id2.Trim();
            //Set value to IdCardNo
            Utils.SetInputValue("IdCardNo", id);
            //If no enter id card no => value = empty
            if (id.Length == 1)
            {
                Utils.SetInputValue("IdCardNo", "");
            }
            //if enter id card no => check format Ex: xxxxxx-xxxxxxx
            if (id.Length > 1)
            {
                if (!UIHelper.ValidateItems(itemRecvIDCardNo, false))
                {
                    Script.Alert(Common.IdCardNoIsWrong);
                    return;
                }
            }
            Utils.SetInputValue("IdCardNo", Utils.GetInputValue("IdCardNo1") + "-" + Utils.GetInputValue("IdCardNo2"));

            #endregion

            //Utils.SetInputValue("PictureId", Utils.GetInputValue("PictureId"));


            string action = string.Format("/CheckDuplicateUserName?userName={0}", Utils.GetInputValue("UserName"));
            string href = SC_Common.BasePath + ControllerUrl + action;
            jQuery.GetJSON(href, new Dictionary(), (Function)(object)new GenericOneArgDelegate(delegate(object data)
            {
                Utils.HideProgressBar();
                bool exists = (bool)Script.Literal("data.Exists");
                if (exists)
                {
                    //사용자가 이미 있습니다 exist userName
                    Script.Alert(Common.SC_Account_UserNameExists);
                    JQueryFactory.JQuery("#UserName").Focus();
                    return;
                }
                else
                {
                    UIHelper.SubmitAjax(form, "Post", null, new MvcCallback(delegate(AjaxContext context)
                    {
                        switch (context.request.Executor.ResponseData)
                        {
                            case "00":
                                Script.Alert(Common.OperationSuccess);
                                Window.Navigate("/Account/LogOn");
                                break;
                            default:
                                break;
                        }
                        //if (context.request.Executor.ResponseData == "00")
                        //{
                        //    Script.Alert(Common.OperationSuccess);
                        //    Window.Navigate("/Account/LogOn");
                        //}
                        //else
                        //{
                        //    Script.Alert(Common.OperationFailed);
                        //}
                    }), null);
                }
            }));
        }
    }

    public static void CheckDupticateEmpCode(String empcode)
    {
        string href = SC_Common.BasePath + ControllerUrl + "/CheckDuplicateEmpCode?empcode=" + empcode;
        jQuery.GetJSON(href, new Dictionary(), (Function)(object)new GenericOneArgDelegate(delegate(object data)
        {
            Utils.HideProgressBar();
            bool exists = (bool)Script.Literal("data.Exists");
            if (exists)
            {
                Script.Alert("사번이 이이 있습니다");
                JQueryFactory.JQuery("#EmpCode").Select();
                JQueryFactory.JQuery("#EmpCode").Focus();
                return;
            }
        }));
    }

    public static void CheckDuplicateUserName(String user)
    {
        string href = SC_Common.BasePath + ControllerUrl + "/CheckDuplicateUserName?userName=" + user;
        jQuery.GetJSON(href, new Dictionary(), (Function)(object)new GenericOneArgDelegate(delegate(object data)
        {
            Utils.HideProgressBar();
            bool exists = (bool)Script.Literal("data.Exists");
            if (exists)
            {
                Script.Alert("사용자가 이미 있습니다");
                JQueryFactory.JQuery("#UserName").Focus();
                return;
            }
            else
            {
                //Script.Alert(Common.ApprDoCheckSuccess);
            }
        }));
    }

    #endregion


    #region 환경설정

    /// <summary>
    /// 환경설정 Popup
    /// </summary>
    public static void OpenEnvironmentSet()
    {
        string href = SC_Common.BasePath + ControllerUrl + "/EnvironmentSetPopup";
        Utils.OpenWinCenter("EnvSet", href, 650, 520);
    }

    /// <summary>
    /// Save env set
    /// </summary>
    /// <param name="form"></param>
    public static void SaveEnvironmentSet(Dictionary form)
    {
        DOMElement formEnvSet = Document.GetElementById("formEnvSet");

        // check tab
        if (SC_Common.SelectedTabName == "Tab1" || SC_Common.SelectedTabName == null || SC_Common.SelectedTabName == "")
        {

            Type.SetField(formEnvSet, "action", SC_Common.BasePath + ControllerUrl + "/SaveMyMenu");
        }
        else
        {
            Type.SetField(formEnvSet, "action", SC_Common.BasePath + ControllerUrl + "/ChangePassword");

            ItemInfor[] items = new ItemInfor[]
            {
                new ItemInfor("OldPassword", true, 1212121, null, ValueType.Text, null),
                new ItemInfor("NewPassword", true, 1212121, null, ValueType.Text, null),
                new ItemInfor("ConfirmPassword", true, 1212121, null, ValueType.Text, null)
            };

            if (!UIHelper.ValidateItems(items, true))
            {
                return;
            }

            string newPassword = Utils.GetInputValue("NewPassword");
            string confirmPassword = Utils.GetInputValue("ConfirmPassword");

            if (newPassword != confirmPassword)
            {
                Script.Alert("비밀버호 확인은 다시 확인 하여 주십시오.");
                return;
            }

            if (newPassword.Length < 6)
            {
                Script.Alert("비밀버호가 6자리이상 입력 하여 주십시오.");
                return;
            }
        }

        // submit
        UIHelper.SubmitAjax(form, "Post", null, new MvcCallback(delegate(AjaxContext context)
            {
                if (context.request.Executor.ResponseData == "")
                {
                    Script.Alert(Common.OperationSuccess);
                    Utils.CloseWindow();
                }
                else
                {
                    Script.Alert(context.request.Executor.ResponseData);
                }
            }), null);
    }

    #endregion

    #region 결재이미지 - ApprSignImg

    public static void UpdateApprSignImg(string empCode, string fileId)
    {
        string href = SC_Common.BasePath + ControllerUrl + "/UpdateEmpApprSignImg?empcode=" + empCode + "&fileid=" + fileId;
        UIHelper.LoadAjaxNullEvent(href, null, null);
    }
    #endregion

    #region 원천징수영수증

    /// <summary>
    /// Fix 
    /// </summary>
    public static void FixWithHoldingNames()
    {
        if (Script.Confirm(Common.DoLongrunTaskMsg))
        {
            string href = SC_Common.BasePath + ControllerUrl + "/FixWithHoldingFiles";
            UIHelper.LoadAjax(href, null, new MvcCallback(delegate(AjaxContext context)
            {
              //  Script.Alert(Common.UpdateSignImageAllCompleted);
            }), null);
        }
    }

    #endregion

}
